package com.ldy.core.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import com.alibaba.fastjson.JSONObject;

import cn.hutool.http.HttpRequest;

/**
 * 微信工具
 */
@Component
public class WechatUtil {

	private static final Logger logger = LoggerFactory.getLogger(WechatUtil.class);

	public static String accessToken = null;

	public static Long ExpirehTime = 0l;

	// 获取token
	public static final String GetToken = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";

	// 获取手机号
	public static final String GetUserPhonenumber = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s";

	// 获取用户openId
	public static final String Jscode2session = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code&appid=%s&secret=%s&js_code=%s";
	
	@Value("${wechat.appid:}")
	private String appid;

	@Value("${wechat.secret:}")
	private String secret;

	/**
	 * 获取accessToken
	 * 
	 * @return
	 */
	public String getAccessToken() {
		if (StringUtils.isEmpty(accessToken) || System.currentTimeMillis() > ExpirehTime) {
			JSONObject result = request(String.format(GetToken, appid, secret));
			accessToken = result.getString("access_token");
			if (StringUtils.isEmpty(accessToken)) {
				throw new IllegalArgumentException("获取微信授权异常");
			}
			ExpirehTime = System.currentTimeMillis() + 1000 * 7000;
		}
		return accessToken;
	}

	/**
	 * 获取手机号
	 * 
	 * @return
	 */
	public String getPhoneNumber(String code) {
		String token = getAccessToken();
		JSONObject body = new JSONObject();
		body.put("code", code);
		JSONObject result = requestPost(String.format(GetUserPhonenumber, token), body);
		String errcode = result.getString("errcode");
		Assert.isTrue("0".equals(errcode), "获取微信手机号错误：" + errcode);
		JSONObject phone = result.getJSONObject("phone_info");
		return phone.getString("phoneNumber");
	}
	
	/**
	 * 登录
	 * 
	 * @return
	 */
	public String login(String code) {
		JSONObject result = request(String.format(Jscode2session, appid, secret, code));
		return result.getString("openid");
	}

	/**
	 * 请求
	 * @param url
	 * @return
	 */
	private JSONObject request(String url) {
		logger.info("请求微信api: {}", url);
		String resultJson = HttpRequest.get(url) //
				.header("Accept", "application/json;charset=utf-8")
				.header("Content-Type", "application/json;charset=utf-8").timeout(3000).execute() //
				.body();
		logger.info("请求结果:{}", resultJson);
		return JSONObject.parseObject(resultJson);
	}
	
	/**
	 * post请求
	 * @param url
	 * @return
	 */
	private JSONObject requestPost(String url, JSONObject body) {
		logger.info("请求微信api: {}", url);
		String resultJson = HttpRequest.post(url) //
				.body(body.toJSONString())
				.header("Accept", "application/json;charset=utf-8")
				.header("Content-Type", "application/json;charset=utf-8").timeout(3000).execute() //
				.body();
		logger.info("请求结果:{}", resultJson);
		return JSONObject.parseObject(resultJson);
	}

}
